package com.shun.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author l
 * @date 2021-08-31
 * sentinel 流量和熔断配置
 */
@Slf4j
@Configuration
public class SentinelConfigure {

    private final List<ViewResolver> viewResolverList;

    private final ServerCodecConfigurer serverCodecConfigurer;
    public SentinelConfigure(List<ViewResolver> viewResolverList,ServerCodecConfigurer serverCodecConfigurer){
        this.serverCodecConfigurer = serverCodecConfigurer;
        this.viewResolverList = viewResolverList;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolverList, serverCodecConfigurer);
    }

    /**
     * 配置Sentinel的Filter
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter(){
        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void  init(){
        this.initRule();
    }

    /**
     * 初始化规则
     */
    private void initRule(){
        Set<GatewayFlowRule> rules = new HashSet<GatewayFlowRule>();
        rules.add(new GatewayFlowRule("map").setCount(1).setIntervalSec(1));
        GatewayRuleManager.loadRules(rules);
    }
}
